<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/3/23
 * Time: 15:47
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\api\controller\v1;

use app\common\lib\ArrClass;
use app\common\model\BuddhaOrder;
use app\common\lib\Radom;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\lib\Time;
use app\common\model\MachineCost;
use app\common\model\MallOrder;
use app\common\model\MallOrderGoods;
use app\common\model\MallSpecs;
use app\common\model\MallSpecsValue;
use app\common\model\SpecsSeasoning;
use Htlove\Str;
use think\App;
use think\Exception;
use think\facade\Log;

class Order extends Base
{
    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallOrder();
    }

    /**
     * @return array|\think\response\Json|void
     */
    public function setOrderData()
    {
        $type = $this->request->param('type', 0, 'intval');
        $money = $this->request->param('money', '', 'trim');
        $mark = $this->request->param('mark', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');
        if ($type == 0) {
            return Show::json_show(Status::mini_error, "请选择捐款类型");
        }
        if (!$money) {
            return Show::json_show(Status::mini_error, "请输入捐款金额");
        }
        if (!empty($mark)) {
            $mark = htmlspecialchars($mark);
        }
        if (empty($openid)) {
            return Show::json_show(Status::mini_error, "用户信息不存在");
        }
        $data = [
            "cate_id" => $type,
            "money" => $money,
            "mark" => $mark,
            "openid" => $openid,
            "order_id" => Radom::create_trade_no()
        ];
        try {
            $res = (new BuddhaOrder())->save($data);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "内部错误");
        }
        if ($res) {
            //进行支付
        } else {
            return Show::json_show(Status::mini_error, "内部异常 ");
        }
    }

    /**
     * @return array|\think\response\Json
     */
    public function getOrderByUserList()
    {
        $openid = $this->request->param('openid', "", "trim");
        if (empty($openid)) {
            return Show::json_show(Status::mini_error, "用户信息错误");
        }
        $datetime = $this->request->param('datetime', '', 'trim');
        $day = "本月";
        $where = [];
        if (!empty($datetime)) {
            $y = date('Y', $datetime / 1000);
            $m = date('m', $datetime / 1000);
            $time = Time::startTimeToEndTime($y, $m);
            $where[] = [
                ['o.create_time', "between", $time]
            ];
            if (date('Y-m', $datetime / 1000) != date('Y-m')) {
                $day = date('Y-m', $datetime / 1000) . "月";
            }
        }
//        dump($where);exit();


        try {
            $lists = (new BuddhaOrder())
                ->field("o.id,o.order_id,o.cate_id,o.money,o.create_time,c.id,c.title,o.create_time")
                ->alias('o')
                ->join('buddha_cate c', 'o.cate_id = c.id')
                ->where("openid", $openid)
                ->where($where)
                ->where('payment', 1)->paginate(10)->toArray();
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "订单错误");
        }
        return Show::json_show(Status::mini_normal, "ok", [
            "row" => $lists,
            "day" => $day
        ]);
    }

    public function directOrderToBuy()
    {
        $data = $this->request->param('value');  //选择的首页id
        $money = $this->request->param('money', 0, 'trim,floatval'); //选择后生成的金额
        $machine_id = $this->request->param('machine_id', '', 'trim'); //机器编号
        $typeList = $this->request->param('typeList'); //自定义的口味
        $number = $this->request->param('number', 1, 'intval'); //数量
        //先计算 获取到商品id 然后计算价格
        if (empty($data)) {
            return Show::json_show(Status::mini_error, "请选择");
        }
        if (empty($machine_id)) {
            return Show::json_show(Status::mini_error, "内部异常");
        }
        $type_list = [];
        if (!empty($typeList)) {
            $type_list = array_column($typeList, 'value', 'id');
        }
        $obj_machine_cost = new MachineCost();
        $obj_specs_value = new MallSpecsValue();
        //根据机器编号获取所有商品配置
        $machine_cost = $obj_machine_cost->getMachineCostByMachineIdInfo($machine_id);
        foreach ($data as $v) {
            foreach ($v as $item) {
                $res[] = $item;
            }
        }
        if (empty($res)) {
            return Show::json_show(Status::mini_error, "请选择后支付");
        }
        $specs_ids = array_column($machine_cost, 'specs_id');
        $specs_value = $obj_specs_value->getSpecsValueByList($specs_ids);
        $ids = array_column($specs_value, 'specs_id');
        if (count(array_unique($ids)) > count($res)) {
            return Show::json_show(Status::mini_error, "请选择完毕");
        }


        //查询所选择的商品
        $machine = $obj_machine_cost->getMachineCostByIds($res, $machine_id, 'id,specs_id,money,type,value,stock,machine_id');
        if (empty($machine)) {
            return Show::json_show(Status::mini_error, "机器不存在");
        }
        //查询选择的规格值
        $get_specs = $obj_specs_value->getSpecsValueByList(array_column($machine, 'specs_id'), 'specs');
        $arr = [];
        foreach ($get_specs as $v) {
            $arr[$v['id']] = $v;
        }
        foreach ($machine as $k => $v) {
            $lists[$k] = $v;
            if ($arr[$v['specs_id']]['title'] == '自选') {
                //查询佐料
                $seasoning = (new SpecsSeasoning())->getBaseByListAll(["status" => 1], '*', "id asc");
                $lists_type = [];
                foreach ($seasoning as $vv) {
                    $lists_type[$vv['id']] = [
                        "key" => $vv['value']
                    ];

                    if ($type_list[$vv['id']] == 100) {
                        $lists_type[$vv['id']]['value'] = 0;
                    } else {
                        $lists_type[$vv['id']]['value'] = $type_list[$vv['id']];
                    }
                }
                $lists[$k]['list_type'] = $lists_type;
            }
            $lists[$k]['specs'] = $arr[$v['specs_id']];
        }
        $order_price = floatval(array_sum(array_column($lists, 'money')));

        $this->model->startTrans();
        try {
            //进行保存 下单
            $order_id = Str::getInstance()->RandNumberStr();
            $insert_data = [
                "order_sn" => $order_id,
                "openid" => $this->m_openid,
                "order_price" => $order_price,
                "discount_price" => 0,
                "pay_price" => $order_price,
                "pay_type" => 1,
                "order_status" => 0,
            ];
            $res_id = $this->model->insertGetId($insert_data);
            $insert_order = [];
            foreach ($lists as $k => $v) {
                $insert_order[$k] = [
                    "machine_id" => $machine_id,
                    "order_id" => $res_id,
                    "specs_id" => $v['specs']['id'],
                    "specs_name" => $v['specs']['title'],
                    "specs" => $v['specs']['specs']['id'],
                    "specs_title" => $v['specs']['specs']['title'],
                    "d_value" => $v['value'],
                    "d_type" => $v['specs']['specs']['type'],
                    "create_time" => time()
                ];
                $insert_order[$k]['d_cate'] = 2;
                if (!empty($v['list_type'])) {
                    $insert_order[$k]['d_cate'] = 2;
                    $insert_order[$k]['cate_value'] = json_encode($v['list_type']);
                }
            }
            (new MallOrderGoods())->saveAll($insert_order);
            $this->model->commit();
        } catch (\Exception $e) {
            $this->model->rollback();
            Log::error("api-order-directOrderToBuy:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        //微信下单
        $url = (string)url('/pay/notify/index', [], true, true);
        $order_data = [
            'body' => '购买商品',
            'out_trade_no' => $order_id,
            'total_fee' => $order_price * 100,
            'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => $url, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $this->m_openid,
        ];
        //设置交易结束时间
        $time = sysconfig('shop', 'order_time');
        $time = (int)$time ?? 15;
        $second = ($time * 60) - 30;
        $end_time = time() + $second;
        $order_data['time_expire'] = date('YmdHis', $end_time);

        $result = $this->payment($order_data);
        return Show::json_show(Status::mini_normal, "ok", Show::json_decode($result));

    }

    /**
     * @param array $order_data
     * @return mixed
     * @throws Exception
     * @throws \ReflectionException
     */
    protected function payment(array $order_data = [])
    {
        $arr = ArrClass::payAttr();
        $obj = ArrClass::initClass('wx', $arr, [], true);
        Log::info("===============用户下单===============");
        $result = $obj->order($order_data);
        Log::info("===============用户下单返回结果===============" . Show::json_encode($result));

        if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
            throw new Exception("系统下单错误");
        }
        Log::info("===============生成支付===============");
        return $obj->jssdk($result['prepay_id']);
    }
}